const { defineConfig } = require('@vue/cli-service');
const path = require("path");
const CopyWebpackPlugin = require('copy-webpack-plugin');
const pages = require("./build/pages");
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const { pageName } = require("./package");
const CompressionPlugin = require("compression-webpack-plugin");

const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const { ElementPlusResolver } = require('unplugin-vue-components/resolvers')

function resolve(dir) {
  return path.join(__dirname, dir);
}

function getPages(pages){
  let find = process.argv.find(item=>{
    console.log(item)
    return item.indexOf('--page=')>-1
  })
  const key = find?find.replace('--page=',''):null;
  return pages[key]?{[key]:pages[key]}:pages
}//配合package命令行用来过滤需要运行的page

//process.env.npm_config_argv  process.argv
module.exports = defineConfig({
  pages: getPages(pages),
  publicPath: "/",
  outputDir: "dist",
  assetsDir: "static",
  filenameHashing: true,
  lintOnSave: true,
  transpileDependencies: true,
  devServer: {
    headers: {
      "Access-Control-Allow-Origin": "*"
    },
    port: "8888",
    proxy: {
      // ["/auth"]: {
      //   target: "http://tenant-gateway.bdn-yunbu-dev.rootcloudapp.com",
      //   ws: true,
      //   changeOrigin: true,
      //   pathRewrite: {
      //     "^/auth": "/auth"
      //   }
      // },
    }
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: '问卷星',
    resolve: {
      alias: {
        "@": resolve("src"),
        "$": resolve("./"),
        'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
      }
    },
    entry: {

    },
    output: {
      // 把子应用打包成 umd 库格式
      library: `${pageName}-[pageName]`,
      libraryTarget: "umd"
    },
    plugins: [
      new CopyWebpackPlugin({
        patterns: [
          {
            from: path.join(__dirname, 'pages'),
            to: 'pages'
          }
        ],
      }),// 打包时带上静态页面目录
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ]
  },
  chainWebpack(config) {
    // config
    //   .plugin('html')
    //   .tap(args => {
    //     args[0].title= '淘海拾贝';
    //     console.log(args)
    //     return args
    //   })

    // 开启js、css压缩
    if (process.env.NODE_ENV !== 'development') {
      config.plugin('compressionPlugin')
        .use(new CompressionPlugin({
          test: /\.js$|\.html$|.\css/, // 匹配文件名
          threshold: 10240, // 对超过10k的数据压缩
          deleteOriginalAssets: false // 不删除源文件
        }))
    }

    // it can improve the speed of the first screen, it is recommended to turn on preload
    config.plugin("preload").use(PreloadWebpackPlugin).tap(() => [
      {
        rel: "preload",
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: "initial"
      }
    ]);
    // Object.keys(pages).forEach(name => {
    //   config.plugin(`preload-${name}`).use("html-webpack-plugin").tap(() => [
    //     {
    //         rel: "preload",
    //         fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
    //         include: "initial"
    //     }
    //   ])
    // })



    // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete("prefetch");

    config.module
      .rule("svg")
      .exclude.add(resolve("src/icons"))
      .end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]"
      })
      .end();
      
    config.plugin('ScriptExtHtmlWebpackPlugin')
      .after('html')
      .use('script-ext-html-webpack-plugin', [
        {
          // `runtime` must same as runtimeChunk name. default is `runtime`
          inline: /runtime\..*\.js$/
        }
      ])
      .end()

    config.module.rule('images')
      .test(/\.(png|gif|jpe?g)(\?.*)?$/)
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({
        bypassOnDebug: true
      })
      .tap(options => Object.assign(options, {
        limit: 6140
      }))
      .end()
    
    
    config.when(process.env.NODE_ENV !== "development", config => {
      config.optimization.splitChunks({
        chunks: "all",
        cacheGroups: {
          libs: {
            name: "chunk-libs",
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: "initial" // only package third parties that are initially dependent
          },
          // elementUI: {
          //   name: "chunk-elementUI", // split elementUI into a single package
          //   priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
          //   test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
          // },
          commons: {
            name: "chunk-commons",
            test: resolve("src/components"), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      });
      // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
      config.optimization.runtimeChunk("single");
    });
  }
})
